#:!/bin/bash

BASE_DIR=$(cd $(dirname $0); pwd)
echo "Base dir $BASE_DIR"

# 启动的 jar 名称
APP_NAME=jarName
SERVER_NAME=${APP_NAME}.jar
SERVER_PATH=$SERVER_NAME
SERVER_LOG_OUT=${BASE_DIR}/logs/${APP_NAME}.log

JAVA_OPT=""
# 设置最小堆内存 最大堆内存 年轻代堆内存 初始化元空间内存  最大元空间内存
# JAVA_OPT="-Xms1024m -Xmx1024m -Xmn512m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=128m"
# 设置内存溢出打印堆日志
JAVA_OPT="${JAVA_OPT} -XX:-OmitStackTraceInFastThrow -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${BASE_DIR}/logs/heapdump.hprof"
# 设置 GC 输出日志
JAVA_OPT="${JAVA_OPT} -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -Xloggc:${BASE_DIR}/logs/${APP_NAME}-gc.log"
SPRING_OPT=" --spring.profiles.active=prod"
# 设置启动程序的 Spring 配置信息
JAVA_OPT="${JAVA_OPT} -jar ${SERVER_PATH} ${SPRING_OPT}"

function start() {
    echo "#############################################################"

    PID=$(ps -ef | grep $SERVER_NAME | grep -v grep | awk "{ print $2 }")
    if [ -z "$PID" ]
	    then
	    echo "Application is starting"
    else
	    echo "Startup failed, application is already running in $CURRENT_DIR, pid=$PID"
	    exit 1
    fi

    echo "java -version"
    java -version

    echo "-----print JAVA_OPT------"
    echo $JAVA_OPT
    nohup java $JAVA_OPT >$SERVER_LOG_OUT 2>&1 &
    tail -f $SERVER_LOG_OUT
}

function stop() {
    PID=$(ps -ef | grep $SERVER_NAME | grep -v grep | awk '{ print $2 }')
    if [ -z "$PID" ]
	    then
	    echo "Application is already stopped"
    else
	    echo "kill -9 $PID"
	    sudo kill -9 $PID
    fi
}

# 根据启动脚本的第 1 个参数决定调用哪个方法(启动:start;停止:stop,重启:restart)
case $1 in
    start)
      shift 1
      start $@
      ;;
    stop)
      shift 1
      stop
      ;;
    restart)
      shift 1
      stop
      sleep 3
      start $@
      ;;
esac